﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using PK3Model;

namespace OneLine
{
    class Tower
    {
        public Tower(CPK3Model model)
        {
            this.Model = model;
            Random rand = new Random();
            this.Inteligence = (float)(rand.NextDouble() * 0.005);
            this.idleRotation = (float)rand.NextDouble();
            this.CurrentHealth = 100;
        }

        public CPK3Model Model { get; protected set; }

        private Vector3 pos;
        private BoundingSphere sphere;
        public Vector3 Position { get { return pos; } set { pos = value; sphere = new BoundingSphere(pos, 1.5f); } }

        public Matrix Rotation { get; set; }

        public float Inteligence { get; set; }

        public bool IsDead { get; set; }

        public int CurrentHealth { get; set; }

        float speed = 0.01f;
        float idleRotation = 0.0f;
        bool shooting = false;

        public void Update(Wave wave, GameTime gameTime)
        {
            Enemy enemy = null;
            foreach (Enemy e in wave.Enemies)
            {
                if (!e.IsDead && sphere.Contains(e.Position) == ContainmentType.Contains)
                {
                    enemy = e; 
                    break;
                }
            }

            if (enemy != null)
            {
                Vector3 forward = enemy.Position - Position;
                forward.Y = 0;
                forward.Normalize();

                if (shooting)
                {
                    if (Model.isFinishAnimationTorso())
                    {
                        Model.setAnimation("TORSO_STAND");
                        shooting = false;
                    }
                }
                else
                {
                    Model.setAnimation("TORSO_ATTACK");
                    shooting = true;
                    enemy.CurrentHealth -= 25;
                }

                Vector3 newPos = Position + (forward * speed);
                newPos.Z = -newPos.Z;
                //Rotation = Matrix.Lerp(Rotation, Matrix.CreateLookAt(Position, newPos, Vector3.Up), 0.25f);
                Rotation = Matrix.CreateLookAt(Position, newPos, Vector3.Up);
                newPos.Z = -newPos.Z;
            }
            else
            {
                idleRotation += 0.01f;
                Rotation = Matrix.Lerp(Rotation, Matrix.CreateRotationY(idleRotation), 0.25f);
            }

            Model.update(gameTime);
        }
    }
}
